const app = getApp();

Page({
    data: {
        projectId: null,
        projectName: '',
        baseURL: '',
        token: '',
        memberList: [],
        applicationList: [],
        currentTab: 'members',  // 当前选中的标签页
        showUserCard: false,
        currentUser: null
    },

    onLoad: function(options) {
        const baseURL = wx.getStorageSync('baseURL');
        const token = wx.getStorageSync('token');
        
        console.log('页面加载时的baseURL:', baseURL);
        console.log('页面加载时的token:', token);
        
        this.setData({
            baseURL: baseURL,
            token: token,
            projectId: options.id
        });

        // 先获取项目信息
        this.getProjectInfo();
    },

    // 切换标签页
    switchTab: function(e) {
        const tab = e.currentTarget.dataset.tab;
        this.setData({
            currentTab: tab
        });
    },

    // 获取项目信息
    getProjectInfo: function() {
        const that = this;
        console.log('正在获取项目信息，projectId:', that.data.projectId);
        wx.request({
            url: that.data.baseURL + '/xiangmuxinxi/detail/' + that.data.projectId,
            method: 'GET',
            header: {
                'Token': that.data.token
            },
            success: function(res) {
                console.log('获取项目信息响应:', res.data);
                if (res.data.code === 0) {
                    that.setData({
                        projectName: res.data.data.xiangmumingcheng
                    });
                    // 获取项目信息后加载团队成员和申请信息
                    that.loadTeamMembers();
                    that.loadApplications();
                } else {
                    wx.showToast({
                        title: '获取项目信息失败: ' + (res.data.msg || '未知错误'),
                        icon: 'none'
                    });
                }
            },
            fail: function(err) {
                console.error('获取项目信息失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    // 加载团队成员
    loadTeamMembers: function() {
        const that = this;
        console.log('正在加载团队成员，项目名称:', that.data.projectName, '类型:', typeof that.data.projectName);
        wx.request({
            url: that.data.baseURL + '/xiangmushenqing/list',
            method: 'GET',
            header: {
                'Token': that.data.token
            },
            data: {
                xiangmumingcheng: that.data.projectName,
                sfsh: '是'  // 已审核通过的申请
            },
            success: function(res) {
                console.log('加载团队成员响应:', res.data);
                if (res.data && res.data.data && res.data.data.list) {
                  console.log('团队成员原始数据条数:', res.data.data.list.length);
                  if (res.data.data.list.length > 0) {
                    console.log('团队成员原始数据片段:', JSON.stringify(res.data.data.list.slice(0, 3)));
                  }
                } else {
                  console.log('团队成员接口返回数据结构异常:', res.data);
                }
                if (res.data.code === 0) {
                    // 获取每个成员的创业者信息
                    const members = res.data.data.list;
                    const promises = members.map(function(member) {
                        return new Promise((resolve) => {
                            wx.request({
                                url: that.data.baseURL + '/chuangyezhe/query',
                                method: 'GET',
                                header: {
                                    'Token': that.data.token
                                },
                                data: {
                                    xuehao: member.xuehao
                                },
                                success: function(chuangyezheRes) {
                                    if (chuangyezheRes.data.code === 0 && chuangyezheRes.data.data) {
                                        // 处理头像路径
                                        const touxiang = chuangyezheRes.data.data.touxiang;
                                        if (touxiang && touxiang.startsWith('file/')) {
                                            member.touxiang = touxiang.substring(5); // 移除'file/'前缀
                                        } else {
                                            member.touxiang = touxiang;
                                        }
                                    }
                                    resolve(member);
                                },
                                fail: function() {
                                    resolve(member);
                                }
                            });
                        });
                    });

                    Promise.all(promises).then(updatedMembers => {
                        that.setData({
                            memberList: updatedMembers
                        });
                    });
                } else {
                    wx.showToast({
                        title: '加载成员失败: ' + (res.data.msg || '未知错误'),
                        icon: 'none'
                    });
                }
            },
            fail: function(err) {
                console.error('加载团队成员失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    // 加载申请信息
    loadApplications: function() {
        const that = this;
        console.log('正在加载申请信息，项目名称:', that.data.projectName, '类型:', typeof that.data.projectName);
        wx.request({
            url: that.data.baseURL + '/xiangmushenqing/list',
            method: 'GET',
            header: {
                'Token': that.data.token
            },
            data: {
                xiangmumingcheng: that.data.projectName,
                sfsh: '待审核'  // 待审核的申请
            },
            success: function(res) {
                console.log('加载申请信息响应:', res.data);
                if (res.data && res.data.data && res.data.data.list) {
                  console.log('申请信息原始数据条数:', res.data.data.list.length);
                  if (res.data.data.list.length > 0) {
                    console.log('申请信息原始数据片段:', JSON.stringify(res.data.data.list.slice(0, 3)));
                  }
                } else {
                  console.log('申请信息接口返回数据结构异常:', res.data);
                }
                if (res.data.code === 0) {
                    // 获取每个申请者的创业者信息
                    const applications = res.data.data.list;
                    const promises = applications.map(function(application) {
                        return new Promise((resolve) => {
                            wx.request({
                                url: that.data.baseURL + '/chuangyezhe/query',
                                method: 'GET',
                                header: {
                                    'Token': that.data.token
                                },
                                data: {
                                    xuehao: application.xuehao
                                },
                                success: function(chuangyezheRes) {
                                    if (chuangyezheRes.data.code === 0 && chuangyezheRes.data.data) {
                                        // 处理头像路径
                                        const touxiang = chuangyezheRes.data.data.touxiang;
                                        if (touxiang && touxiang.startsWith('file/')) {
                                            application.touxiang = touxiang.substring(5); // 移除'file/'前缀
                                        } else {
                                            application.touxiang = touxiang;
                                        }
                                    }
                                    resolve(application);
                                },
                                fail: function() {
                                    resolve(application);
                                }
                            });
                        });
                    });

                    Promise.all(promises).then(updatedApplications => {
                        that.setData({
                            applicationList: updatedApplications
                        });
                    });
                } else {
                    wx.showToast({
                        title: '加载申请失败: ' + (res.data.msg || '未知错误'),
                        icon: 'none'
                    });
                }
            },
            fail: function(err) {
                console.error('加载申请信息失败:', err);
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    // 移除成员
    removeMember: function(e) {
        const that = this;
        const memberId = e.currentTarget.dataset.id;

        wx.showModal({
            title: '确认移除',
            content: '确定要移除该成员吗？',
            success: function(res) {
                if (res.confirm) {
                    wx.request({
                        url: that.data.baseURL + '/xiangmushenqing/delete',
                        method: 'POST',
                        header: {
                            'Token': that.data.token
                        },
                        data: [memberId],
                        success: function(res) {
                            if (res.data.code === 0) {
                                wx.showToast({
                                    title: '移除成功',
                                    icon: 'success'
                                });
                                that.loadTeamMembers();
                            } else {
                                wx.showToast({
                                    title: '移除失败: ' + (res.data.msg || '未知错误'),
                                    icon: 'none'
                                });
                            }
                        },
                        fail: function() {
                            wx.showToast({
                                title: '网络错误',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        });
    },

    // 处理申请
    handleApplication: function(e) {
        const that = this;
        const applicationId = e.currentTarget.dataset.id;
        const action = e.currentTarget.dataset.action;

        wx.showModal({
            title: action === 'approve' ? '确认通过' : '确认拒绝',
            content: action === 'approve' ? '确定要通过该申请吗？' : '确定要拒绝该申请吗？',
            success: function(res) {
                if (res.confirm) {
                    wx.request({
                        url: that.data.baseURL + '/xiangmushenqing/update',
                        method: 'POST',
                        header: {
                            'Token': that.data.token
                        },
                        data: {
                            id: applicationId,
                            sfsh: action === 'approve' ? '是' : '否'
                        },
                        success: function(res) {
                            if (res.data.code === 0) {
                                wx.showToast({
                                    title: action === 'approve' ? '已通过' : '已拒绝',
                                    icon: 'success'
                                });
                                that.loadApplications();
                                if (action === 'approve') {
                                    that.loadTeamMembers();
                                    // 如果当前在申请信息页面，切换到成员页面
                                    if (that.data.currentTab === 'applications') {
                                        that.setData({
                                            currentTab: 'members'
                                        });
                                    }
                                }
                            } else {
                                wx.showToast({
                                    title: '操作失败: ' + (res.data.msg || '未知错误'),
                                    icon: 'none'
                                });
                            }
                        },
                        fail: function() {
                            wx.showToast({
                                title: '网络错误',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        });
    },

    // 图片加载失败处理
    imageError: function(e) {
        console.error('图片加载失败:', e.detail.errMsg);
        const index = e.currentTarget.dataset.index;
        const type = e.currentTarget.dataset.type;
        console.log('加载失败的图片索引:', index);
        console.log('加载失败的图片类型:', type);
        
        // 重新获取用户信息
        if (type === 'member') {
            const member = this.data.memberList[index];
            this.getChuangyezheInfo(member.xuehao, 'member', index);
        } else if (type === 'applicant') {
            const applicant = this.data.applicationList[index];
            this.getChuangyezheInfo(applicant.xuehao, 'applicant', index);
        }
    },

    // 获取创业者信息
    getChuangyezheInfo: function(xuehao, type, index) {
        const that = this;
        wx.request({
            url: that.data.baseURL + '/chuangyezhe/query',
            method: 'GET',
            header: {
                'Token': that.data.token
            },
            data: {
                xuehao: xuehao
            },
            success: function(res) {
                if (res.data.code === 0 && res.data.data) {
                    // 处理头像路径
                    const touxiang = res.data.data.touxiang;
                    if (touxiang && touxiang.startsWith('file/')) {
                        if (type === 'member') {
                            const memberList = that.data.memberList;
                            memberList[index].touxiang = touxiang.substring(5); // 移除'file/'前缀
                            that.setData({
                                memberList: memberList
                            });
                        } else if (type === 'applicant') {
                            const applicationList = that.data.applicationList;
                            applicationList[index].touxiang = touxiang.substring(5); // 移除'file/'前缀
                            that.setData({
                                applicationList: applicationList
                            });
                        }
                    }
                }
            }
        });
    },

    // 显示用户卡片
    showUserCard(e) {
        const user = e.currentTarget.dataset.user;
        const that = this;
        
        // 获取用户详细信息
        wx.request({
            url: that.data.baseURL + '/chuangyezhe/query',
            method: 'GET',
            header: {
                'Token': that.data.token
            },
            data: {
                xuehao: user.xuehao
            },
            success: function(res) {
                if (res.data.code === 0 && res.data.data) {
                    const userInfo = res.data.data;
                    // 处理头像路径
                    if (userInfo.touxiang && userInfo.touxiang.startsWith('file/')) {
                        userInfo.touxiang = userInfo.touxiang.substring(5);
                    }
                    
                    that.setData({
                        showUserCard: true,
                        currentUser: userInfo
                    });
                } else {
                    wx.showToast({
                        title: '获取用户信息失败',
                        icon: 'none'
                    });
                }
            },
            fail: function() {
                wx.showToast({
                    title: '网络错误',
                    icon: 'none'
                });
            }
        });
    },

    // 隐藏用户卡片
    hideUserCard() {
        this.setData({
            showUserCard: false,
            currentUser: null
        });
    }
}); 